package com.rjwh.dingdong.client.mvp;

import android.content.Context;

import com.aishua.lib.task.AsResult;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by wby on 2016/5/18.
 */
public abstract class BasePresenter<T extends MvpView> {

    private T mMvpView;
    private Context mContext;
    public CompositeSubscription mCompositeSubscription;

    public BasePresenter(Context context, T mMvpView) {
        this.mContext = context;
        this.mMvpView = mMvpView;
        this.mCompositeSubscription = new CompositeSubscription();
    }

    public boolean isViewAttached() {
        return mMvpView != null;
    }


    public T getMvpView() {
        return mMvpView;
    }

    public Context getContext() {
        return mContext;
    }

    public void attachView(T view) {
        this.mMvpView = mMvpView;
    }


    protected void detachViews() {
        this.mMvpView = null;
        this.mContext = null;
        onUnsubscribe();
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }


    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    public abstract void  onServerDataAcquired(int businessType, AsResult mAsResult, boolean isRefresh);

    public abstract void  detachView();

}
